package coffee.provider;

import coffee.provider.bean.MsgHistory;
import coffee.provider.bean.UserBean;
import coffee.sqlite.DbHelper;
import coffee.sqlite.TSqliteUtils;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class AppContentProvider extends ContentProvider {

	private final String TAG = AppContentProvider.class.getCanonicalName();

	public static final String AUTH_ORITIES = "coffee.provider.AppContentProvider";

	private ContentResolver mContentrResolver;

	private UriMatcher uriMatcher;

	@Override
	public boolean onCreate() {
		Log.i(TAG, "onCreate ContentProvider");

		mContentrResolver = getContext().getContentResolver();

		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(AUTH_ORITIES, "insert/*", 1);// 插入 # 匹配表名
		uriMatcher.addURI(AUTH_ORITIES, "delete/*", 2);// 删除 # 匹配表名
		uriMatcher.addURI(AUTH_ORITIES, "update/*", 3);// 更新 .......
		uriMatcher.addURI(AUTH_ORITIES, "query/*", 4); // 查询 ......

		int result = uriMatcher.match(Uri.parse("content://" + AUTH_ORITIES
				+ "/insert/1"));
		System.out.println(result);
		return true;
	}

	private String getTableName(Uri uri) {
		String tableName = uri.toString().substring(
				uri.toString().lastIndexOf("/") + 1);
		return tableName;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {

		DbHelper dbHelper = new DbHelper();

		Cursor cursor = dbHelper.getReadableDatabase().query(getTableName(uri),
				projection, selection, selectionArgs, null, null, sortOrder);

		return cursor;
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		DbHelper db = new DbHelper();

		if ("msg_history".equals(getTableName(uri))) {
			MsgHistory msg = TSqliteUtils.processContentValesToT(values,
					MsgHistory.class);
			db.insert(msg);
			db.close();
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return null;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		return 0;
	}

}
